package com.test.langchain4j.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import dev.langchain4j.community.model.dashscope.WanxImageModel;
import dev.langchain4j.data.image.Image;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.output.Response;
import java.io.IOException;
import java.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 2025/7/31 10:33
 * @modifiedBy:
 * @version: 1.0
 */
@RestController
@Slf4j
public class ImageModelController {
  @Autowired private ChatModel chatModel;
  @Autowired private WanxImageModel wanxImageModel;

  @Value("classpath:static/images/mi_yu7.png")
  private Resource resource;

  /**
   * @Description: 通过Base64编码将图片转化为字符串，结合ImageContent和TextContent 一起发送到模型进行处理。 @Author:
   * zzyybs@126.com 测试地址：http://localhost:9006/image/call
   */
  @GetMapping(value = "/image/call")
  public String readImageContent() throws IOException {
    // 第一步，图片转化为Base64字符串
    byte[] byteArray = resource.getContentAsByteArray();
    String base64Data = Base64.getEncoder().encodeToString(byteArray);

    // 第二步，创建UserMessage，包含文本内容和图片内容，结合ImageContent和TextContent一起发送到模型进行处理
    // 注意：这里的图片格式需要和实际图片格式一致，比如image/png或image/jpeg等
    UserMessage userMessage =
        UserMessage.from(
            TextContent.from("从以下图片中识别车辆的厂商和型号，并根据识别结果进行车辆的简介"),
            ImageContent.from(base64Data, "image/png"));

    // 第三步,API调用，使用OpenAiChatModel来构建请求，并通过chat()方法调用模型
    // 请求内容包括文本提示和图片，模型会根据输入返回分析结果
    ChatResponse chatResponse = chatModel.chat(userMessage);

    // 第四步，解析用户输出：从ChatResponse中获取AI的回复内容,打印出处理后的结果
    String result = chatResponse.aiMessage().text();

    // 输出结果到控制台
    System.out.println(result);

    // 返回处理结果
    return result;
  }

  // http://localhost:9006/image/create2
  @GetMapping(value = "/image/create2")
  public String createImageContent2() throws IOException {
    System.out.println(wanxImageModel);
    Response<Image> imageResponse = wanxImageModel.generate("美女");
    System.out.println(imageResponse.content().url());
    return imageResponse.content().url().toString();
  }

  @GetMapping(value = "/image/create3")
  public String createImageContent3() throws IOException {
    String prompt = "近景镜头，18岁的中国女孩，古代服饰，圆脸，正面看着镜头，" + "民族优雅的服装，商业摄影，室外，电影级光照，半身特写，精致的淡妆，锐利的边缘。";
    ImageSynthesisParam param =
        ImageSynthesisParam.builder()
            .apiKey(System.getenv("qwen-api-key"))
            .model(ImageSynthesis.Models.WANX_V1)
            .prompt(prompt)
            .style("<watercolor>")
            .n(1)
            .size("1024*1024")
            .build();

    ImageSynthesis imageSynthesis = new ImageSynthesis();
    ImageSynthesisResult result;
    try {
      System.out.println("---sync call, please wait a moment----");
      result = imageSynthesis.call(param);
    } catch (ApiException | NoApiKeyException e) {
      throw new RuntimeException(e.getMessage());
    }

    System.out.println(JsonUtils.toJson(result));

    return JsonUtils.toJson(result);
  }
}
